package com.example.common.tools

import android.app.Activity
import android.content.Intent
import android.net.Uri
import com.example.common.soundutil.util.FileUtils
import com.zhy.base.fileprovider.FileProvider7
import java.io.*
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*

class FileUtil {

    var appFilePach: String? = null

    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            FileUtil()
        }

    }

    fun createFile(fileName: String): File? {
        val dirsFile = File(TooldUtils.getRingtonesPath())
        if (!dirsFile.exists()) {
            dirsFile.mkdirs()
        }
        //Log.i("创建文件","创建文件");
        val file =
            File(dirsFile.toString(), fileName)// MYLOG_PATH_SDCARD_DIR
        if (!file.exists()) {
            try {
                //在指定的文件夹中创建文件
                file.createNewFile()
            } catch (e: Exception) {
            }
        }
        return file
    }

    var list = LinkedList<File>()
    fun getFilesByPath(dir: String): LinkedList<File> {
        val file = File(dir)
        if (file.exists()) {
            if (file.isDirectory) {
                var listFiles = file.listFiles()
                for (pathFile in listFiles) {
                    LogUtils.eLog("file", "文件 ==  $pathFile")
                    getFilesByPath(pathFile.absolutePath)
                }
            } else {
                list.add(file)
            }
        }
        return list
    }


    //判断文件目录是否可以创建
    fun isCreatePath(filePath: String): String? {
        var filePath = filePath
        if (!FileUtils.createOrExistsDir(filePath)) {
            LogUtils.eLog("TAG", "文件夹创建失败 ：$filePath")
            filePath = ""
        }
        LogUtils.eLog("TAG", "文件夹目录 ：$filePath")
        return filePath
    }

    /**
     * app 安装包MD5校验
     */
    @Throws(NoSuchAlgorithmException::class, IOException::class)
    fun getMD5(file: File): String? {
        if (!file.isFile) {
            return null
        }
        val digest: MessageDigest = MessageDigest.getInstance("MD5")
        val input = FileInputStream(file)
        val buffer = ByteArray(2048)
        var len: Int = -1
        input.use { inp ->
            while (run {
                    len = inp.read(buffer, 0, 2048)
                    len
                } != -1) {
                digest.update(buffer, 0, len)
            }
        }
        while (len != -1) {
            digest.update(buffer, 0, len)
        }
        input.close()
        val formatter = Formatter()
        for (b in digest.digest()) {
            formatter.format("%02x", b)
        }
        return formatter.toString()
    }

    /**
     * file转ByteArray
     */
    fun file2byte(file: File): ByteArray? {
        val byte_size = 1024
        val b = ByteArray(byte_size)
        try {
            val fileInputStream = FileInputStream(file)
            val outputStream = ByteArrayOutputStream(
                byte_size
            )
            var length: Int
            while (fileInputStream.read(b).also { length = it } != -1) {
                outputStream.write(b, 0, length)
            }
            fileInputStream.close()
            outputStream.close()
            return outputStream.toByteArray()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    fun fileCopy(oldFile: File, newFilePath: String): File? {
        //如果原文件不存在
        if (oldFile == null || !oldFile.exists()) {
            return null
        }
        //获得原文件流
        val inputStream: FileInputStream = FileInputStream(oldFile)
        val data = ByteArray(1024)
        //输出流
        var newFile = File(newFilePath)
        val outputStream = FileOutputStream(newFile)
        //开始处理流
        while (inputStream.read(data) != -1) {
            outputStream.write(data)
        }
        inputStream.close()
        outputStream.close()
        return newFile
    }

}

fun Activity.openFile(file: File) {
    val uri = FileProvider7.getUriForFile(this,file)
//    var uri = Uri.fromFile(file)
    var intent = Intent(Intent.ACTION_VIEW)
    LogUtils.eLog("file","音频url---->${uri}")
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    intent.putExtra("oneshot", 0)
    intent.putExtra("configchange", 0)
    intent.setDataAndType(uri, "audio/*")
    startActivity(intent)
}

fun Activity.openFile(filePash: String) {
    val uri = FileProvider7.getUriForFile(this, File(filePash))
    val intent = Intent(Intent.ACTION_GET_CONTENT)
    intent.addCategory(Intent.CATEGORY_DEFAULT)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    intent.setDataAndType(uri, "file/*")
    startActivity(intent)
}

